<!doctype html>

<html>
<head>
  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>annotate.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <script>
     var _staticFilePath = "static/";
     var _typeTreeName = "goog";
     var _fileTreeName = "Source";
  </script>

  <script src="static/js/doc.js">
  </script>


  <meta charset="utf8">
</head>

<body onload="grokdoc.onLoad();">

<div id="header">
  <div class="g-section g-tpl-50-50 g-split">
    <div class="g-unit g-first">
      <a id="logo" href="index.html">Closure Library API Documentation</a>
    </div>

    <div class="g-unit">
      <div class="g-c">
        <strong>Go to class or file:</strong>
        <input type="text" id="ac">
      </div>
    </div>
  </div>
</div>

<div class="clear"></div>

<h2><a href="local_closure_goog_dom_annotate.js.html">annotate.js</a></h2>

<pre class="prettyprint lang-js">
<a name="line1"></a>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
<a name="line2"></a>//
<a name="line3"></a>// Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
<a name="line4"></a>// you may not use this file except in compliance with the License.
<a name="line5"></a>// You may obtain a copy of the License at
<a name="line6"></a>//
<a name="line7"></a>//      http://www.apache.org/licenses/LICENSE-2.0
<a name="line8"></a>//
<a name="line9"></a>// Unless required by applicable law or agreed to in writing, software
<a name="line10"></a>// distributed under the License is distributed on an &quot;AS-IS&quot; BASIS,
<a name="line11"></a>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<a name="line12"></a>// See the License for the specific language governing permissions and
<a name="line13"></a>// limitations under the License.
<a name="line14"></a>
<a name="line15"></a>/**
<a name="line16"></a> * @fileoverview Methods for annotating occurrences of query terms in text or
<a name="line17"></a> *   in a DOM tree. Adapted from Gmail code.
<a name="line18"></a> *
<a name="line19"></a> */
<a name="line20"></a>
<a name="line21"></a>goog.provide(&#39;goog.dom.annotate&#39;);
<a name="line22"></a>
<a name="line23"></a>goog.require(&#39;goog.array&#39;);
<a name="line24"></a>goog.require(&#39;goog.dom&#39;);
<a name="line25"></a>goog.require(&#39;goog.dom.NodeType&#39;);
<a name="line26"></a>goog.require(&#39;goog.string&#39;);
<a name="line27"></a>
<a name="line28"></a>
<a name="line29"></a>/**
<a name="line30"></a> * Calls {@code annotateFn} for each occurrence of a search term in text nodes
<a name="line31"></a> * under {@code node}. Returns the number of hits.
<a name="line32"></a> *
<a name="line33"></a> * @param {Node} node  A DOM node.
<a name="line34"></a> * @param {Array} terms  An array of [searchTerm, matchWholeWordOnly] tuples.
<a name="line35"></a> *   The matchWholeWordOnly value is a per-term attribute because some terms
<a name="line36"></a> *   may be CJK, while others are not. (For correctness, matchWholeWordOnly
<a name="line37"></a> *   should always be false for CJK terms.).
<a name="line38"></a> * @param {Function} annotateFn  A function that takes
<a name="line39"></a> *   (1) the number of the term that is &quot;hit&quot;,
<a name="line40"></a> *   (2) the HTML string (search term) to be annotated,
<a name="line41"></a> *   and returns the annotated term as an HTML string.
<a name="line42"></a> * @param {*=} opt_ignoreCase  Whether to ignore the case of the query
<a name="line43"></a> *   terms when looking for matches.
<a name="line44"></a> * @param {Array.&lt;string&gt;=} opt_classesToSkip  Nodes with one of these CSS class
<a name="line45"></a> *   names (and its descendants) will be skipped.
<a name="line46"></a> * @param {number=} opt_maxMs  Number of milliseconds after which this function,
<a name="line47"></a> *   if still annotating, should stop and return.
<a name="line48"></a> *
<a name="line49"></a> * @return {boolean} Whether any terms were annotated.
<a name="line50"></a> */
<a name="line51"></a>goog.dom.annotate.annotateTerms = function(node, terms, annotateFn,
<a name="line52"></a>                                           opt_ignoreCase,
<a name="line53"></a>                                           opt_classesToSkip,
<a name="line54"></a>                                           opt_maxMs) {
<a name="line55"></a>  if (opt_ignoreCase) {
<a name="line56"></a>    terms = goog.dom.annotate.lowercaseTerms_(terms);
<a name="line57"></a>  }
<a name="line58"></a>  var stopTime = opt_maxMs &gt; 0 ? goog.now() + opt_maxMs : 0;
<a name="line59"></a>
<a name="line60"></a>  return goog.dom.annotate.annotateTermsInNode_(
<a name="line61"></a>      node, terms, annotateFn, opt_ignoreCase, opt_classesToSkip || [],
<a name="line62"></a>      stopTime, 0);
<a name="line63"></a>};
<a name="line64"></a>
<a name="line65"></a>
<a name="line66"></a>/**
<a name="line67"></a> * The maximum recursion depth allowed. Any DOM nodes deeper than this are
<a name="line68"></a> * ignored.
<a name="line69"></a> * @type {number}
<a name="line70"></a> * @private
<a name="line71"></a> */
<a name="line72"></a>goog.dom.annotate.MAX_RECURSION_ = 200;
<a name="line73"></a>
<a name="line74"></a>
<a name="line75"></a>/**
<a name="line76"></a> * The node types whose descendants should not be affected by annotation.
<a name="line77"></a> * @type {Array}
<a name="line78"></a> * @private
<a name="line79"></a> */
<a name="line80"></a>goog.dom.annotate.NODES_TO_SKIP_ = [&#39;SCRIPT&#39;, &#39;STYLE&#39;, &#39;TEXTAREA&#39;];
<a name="line81"></a>
<a name="line82"></a>
<a name="line83"></a>/**
<a name="line84"></a> * Recursive helper function.
<a name="line85"></a> *
<a name="line86"></a> * @param {Node} node  A DOM node.
<a name="line87"></a> * @param {Array} terms  An array of [searchTerm, matchWholeWordOnly] tuples.
<a name="line88"></a> *     The matchWholeWordOnly value is a per-term attribute because some terms
<a name="line89"></a> *     may be CJK, while others are not. (For correctness, matchWholeWordOnly
<a name="line90"></a> *     should always be false for CJK terms.).
<a name="line91"></a> * @param {Function} annotateFn  function(number, string) : string  A function
<a name="line92"></a> *     that takes :
<a name="line93"></a> *     (1) the number of the term that is &quot;hit&quot;,
<a name="line94"></a> *     (2) the HTML string (search term) to be annotated,
<a name="line95"></a> *     and returns the annotated term as an HTML string.
<a name="line96"></a> * @param {*} ignoreCase  Whether to ignore the case of the query terms
<a name="line97"></a> *     when looking for matches.
<a name="line98"></a> * @param {Array.&lt;string&gt;} classesToSkip  Nodes with one of these CSS class
<a name="line99"></a> *     names will be skipped (as will their descendants).
<a name="line100"></a> * @param {number} stopTime  Deadline for annotation operation (ignored if 0).
<a name="line101"></a> * @param {number} recursionLevel  How deep this recursive call is; pass the
<a name="line102"></a> *     value 0 in the initial call.
<a name="line103"></a> * @return {boolean} Whether any terms were annotated.
<a name="line104"></a> * @private
<a name="line105"></a> */
<a name="line106"></a>goog.dom.annotate.annotateTermsInNode_ =
<a name="line107"></a>    function(node, terms, annotateFn, ignoreCase, classesToSkip,
<a name="line108"></a>             stopTime, recursionLevel) {
<a name="line109"></a>  if ((stopTime &gt; 0 &amp;&amp; goog.now() &gt;= stopTime) ||
<a name="line110"></a>      recursionLevel &gt; goog.dom.annotate.MAX_RECURSION_) {
<a name="line111"></a>    return false;
<a name="line112"></a>  }
<a name="line113"></a>
<a name="line114"></a>  var annotated = false;
<a name="line115"></a>
<a name="line116"></a>  if (node.nodeType == goog.dom.NodeType.TEXT) {
<a name="line117"></a>    var html = goog.dom.annotate.helpAnnotateText_(node.nodeValue, terms,
<a name="line118"></a>                                                   annotateFn, ignoreCase);
<a name="line119"></a>    if (html != null) {
<a name="line120"></a>      // Replace the text with the annotated html. First we put the html into
<a name="line121"></a>      // a temporary node, to get its DOM structure. To avoid adding a wrapper
<a name="line122"></a>      // element as a side effect, we&#39;ll only actually use the temporary node&#39;s
<a name="line123"></a>      // children.
<a name="line124"></a>      var tempNode = goog.dom.getOwnerDocument(node).createElement(&#39;SPAN&#39;);
<a name="line125"></a>      tempNode.innerHTML = html;
<a name="line126"></a>
<a name="line127"></a>      var parentNode = node.parentNode;
<a name="line128"></a>      var nodeToInsert;
<a name="line129"></a>      while ((nodeToInsert = tempNode.firstChild) != null) {
<a name="line130"></a>        // Each parentNode.insertBefore call removes the inserted node from
<a name="line131"></a>        // tempNode&#39;s list of children.
<a name="line132"></a>        parentNode.insertBefore(nodeToInsert, node);
<a name="line133"></a>      }
<a name="line134"></a>
<a name="line135"></a>      parentNode.removeChild(node);
<a name="line136"></a>      annotated = true;
<a name="line137"></a>    }
<a name="line138"></a>  } else if (node.hasChildNodes() &amp;&amp;
<a name="line139"></a>             !goog.array.contains(goog.dom.annotate.NODES_TO_SKIP_,
<a name="line140"></a>                 node.tagName)) {
<a name="line141"></a>    var classes = node.className.split(/\s+/);
<a name="line142"></a>    var skip = goog.array.some(classes, function(className) {
<a name="line143"></a>      return goog.array.contains(classesToSkip, className);
<a name="line144"></a>    });
<a name="line145"></a>
<a name="line146"></a>    if (!skip) {
<a name="line147"></a>      ++recursionLevel;
<a name="line148"></a>      var curNode = node.firstChild;
<a name="line149"></a>      var numTermsAnnotated = 0;
<a name="line150"></a>      while (curNode) {
<a name="line151"></a>        var nextNode = curNode.nextSibling;
<a name="line152"></a>        var curNodeAnnotated = goog.dom.annotate.annotateTermsInNode_(
<a name="line153"></a>            curNode, terms, annotateFn, ignoreCase, classesToSkip,
<a name="line154"></a>            stopTime, recursionLevel);
<a name="line155"></a>        annotated = annotated || curNodeAnnotated;
<a name="line156"></a>        curNode = nextNode;
<a name="line157"></a>      }
<a name="line158"></a>    }
<a name="line159"></a>  }
<a name="line160"></a>
<a name="line161"></a>  return annotated;
<a name="line162"></a>};
<a name="line163"></a>
<a name="line164"></a>
<a name="line165"></a>/**
<a name="line166"></a> * Regular expression that matches non-word characters.
<a name="line167"></a> *
<a name="line168"></a> * Performance note: Testing a one-character string using this regex is as fast
<a name="line169"></a> * as the equivalent string test (&quot;a-zA-Z0-9_&quot;.indexOf(c) &lt; 0), give or take a
<a name="line170"></a> * few percent. (The regex is about 5% faster in IE 6 and about 4% slower in
<a name="line171"></a> * Firefox 1.5.) If performance becomes critical, it may be better to convert
<a name="line172"></a> * the character to a numerical char code and check whether it falls in the
<a name="line173"></a> * word character ranges. A quick test suggests that could be 33% faster.
<a name="line174"></a> *
<a name="line175"></a> * @type {RegExp}
<a name="line176"></a> * @private
<a name="line177"></a> */
<a name="line178"></a>goog.dom.annotate.NONWORD_RE_ = /\W/;
<a name="line179"></a>
<a name="line180"></a>
<a name="line181"></a>/**
<a name="line182"></a> * Annotates occurrences of query terms in plain text. This process consists of
<a name="line183"></a> * identifying all occurrences of all query terms, calling a provided function
<a name="line184"></a> * to get the appropriate replacement HTML for each occurrence, and
<a name="line185"></a> * HTML-escaping all the text.
<a name="line186"></a> *
<a name="line187"></a> * @param {string} text  The plain text to be searched.
<a name="line188"></a> * @param {Array} terms  An array of
<a name="line189"></a> *   [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
<a name="line190"></a> *   The matchWholeWordOnly value is a per-term attribute because some terms
<a name="line191"></a> *   may be CJK, while others are not. (For correctness, matchWholeWordOnly
<a name="line192"></a> *   should always be false for CJK terms.).
<a name="line193"></a> * @param {Function} annotateFn {function(number, string) : string} A function
<a name="line194"></a> *   that takes
<a name="line195"></a> *   (1) the number of the term that is &quot;hit&quot;,
<a name="line196"></a> *   (2) the HTML string (search term) to be annotated,
<a name="line197"></a> *   and returns the annotated term as an HTML string.
<a name="line198"></a> * @param {*=} opt_ignoreCase  Whether to ignore the case of the query
<a name="line199"></a> *   terms when looking for matches.
<a name="line200"></a> * @return {?string} The HTML equivalent of {@code text} with terms
<a name="line201"></a> *   annotated, or null if the text did not contain any of the terms.
<a name="line202"></a> */
<a name="line203"></a>goog.dom.annotate.annotateText = function(text, terms, annotateFn,
<a name="line204"></a>                                          opt_ignoreCase) {
<a name="line205"></a>  if (opt_ignoreCase) {
<a name="line206"></a>    terms = goog.dom.annotate.lowercaseTerms_(terms);
<a name="line207"></a>  }
<a name="line208"></a>  return goog.dom.annotate.helpAnnotateText_(text, terms, annotateFn,
<a name="line209"></a>                                             opt_ignoreCase);
<a name="line210"></a>};
<a name="line211"></a>
<a name="line212"></a>
<a name="line213"></a>/**
<a name="line214"></a> * Annotates occurrences of query terms in plain text. This process consists of
<a name="line215"></a> * identifying all occurrences of all query terms, calling a provided function
<a name="line216"></a> * to get the appropriate replacement HTML for each occurrence, and
<a name="line217"></a> * HTML-escaping all the text.
<a name="line218"></a> *
<a name="line219"></a> * @param {string} text  The plain text to be searched.
<a name="line220"></a> * @param {Array} terms  An array of
<a name="line221"></a> *   [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
<a name="line222"></a> *   If {@code ignoreCase} is true, each search term must already be lowercase.
<a name="line223"></a> *   The matchWholeWordOnly value is a per-term attribute because some terms
<a name="line224"></a> *   may be CJK, while others are not. (For correctness, matchWholeWordOnly
<a name="line225"></a> *   should always be false for CJK terms.).
<a name="line226"></a> * @param {Function} annotateFn {function(number, string) : string} A function
<a name="line227"></a> *   that takes
<a name="line228"></a> *   (1) the number of the term that is &quot;hit&quot;,
<a name="line229"></a> *   (2) the HTML string (search term) to be annotated,
<a name="line230"></a> *   and returns the annotated term as an HTML string.
<a name="line231"></a> * @param {*} ignoreCase  Whether to ignore the case of the query terms
<a name="line232"></a> *   when looking for matches.
<a name="line233"></a> * @return {?string} The HTML equivalent of {@code text} with terms
<a name="line234"></a> *   annotated, or null if the text did not contain any of the terms.
<a name="line235"></a> * @private
<a name="line236"></a> */
<a name="line237"></a>goog.dom.annotate.helpAnnotateText_ = function(text, terms, annotateFn,
<a name="line238"></a>                                               ignoreCase) {
<a name="line239"></a>  var hit = false;
<a name="line240"></a>  var resultHtml = null;
<a name="line241"></a>  var textToSearch = ignoreCase ? text.toLowerCase() : text;
<a name="line242"></a>  var textLen = textToSearch.length;
<a name="line243"></a>  var numTerms = terms.length;
<a name="line244"></a>
<a name="line245"></a>  // Each element will be an array of hit positions for the term.
<a name="line246"></a>  var termHits = new Array(numTerms);
<a name="line247"></a>
<a name="line248"></a>  // First collect all the hits into allHits.
<a name="line249"></a>  for (var i = 0; i &lt; numTerms; i++) {
<a name="line250"></a>    var term = terms[i];
<a name="line251"></a>    var hits = [];
<a name="line252"></a>    var termText = term[0];
<a name="line253"></a>    if (termText != &#39;&#39;) {
<a name="line254"></a>      var matchWholeWordOnly = term[1];
<a name="line255"></a>      var termLen = termText.length;
<a name="line256"></a>      var pos = 0;
<a name="line257"></a>      // Find each hit for term t and append to termHits.
<a name="line258"></a>      while (pos &lt; textLen) {
<a name="line259"></a>        var hitPos = textToSearch.indexOf(termText, pos);
<a name="line260"></a>        if (hitPos == -1) {
<a name="line261"></a>          break;
<a name="line262"></a>        } else {
<a name="line263"></a>          var prevCharPos = hitPos - 1;
<a name="line264"></a>          var nextCharPos = hitPos + termLen;
<a name="line265"></a>          if (!matchWholeWordOnly ||
<a name="line266"></a>              ((prevCharPos &lt; 0 ||
<a name="line267"></a>                goog.dom.annotate.NONWORD_RE_.test(
<a name="line268"></a>                    textToSearch.charAt(prevCharPos))) &amp;&amp;
<a name="line269"></a>               (nextCharPos &gt;= textLen ||
<a name="line270"></a>                goog.dom.annotate.NONWORD_RE_.test(
<a name="line271"></a>                    textToSearch.charAt(nextCharPos))))) {
<a name="line272"></a>            hits.push(hitPos);
<a name="line273"></a>            hit = true;
<a name="line274"></a>          }
<a name="line275"></a>          pos = hitPos + termLen;
<a name="line276"></a>        }
<a name="line277"></a>      }
<a name="line278"></a>    }
<a name="line279"></a>    termHits[i] = hits;
<a name="line280"></a>  }
<a name="line281"></a>
<a name="line282"></a>  if (hit) {
<a name="line283"></a>    var html = [];
<a name="line284"></a>    var pos = 0;
<a name="line285"></a>
<a name="line286"></a>    while (true) {
<a name="line287"></a>      // First determine which of the n terms is the next hit.
<a name="line288"></a>      var termIndexOfNextHit;
<a name="line289"></a>      var posOfNextHit = -1;
<a name="line290"></a>
<a name="line291"></a>      for (var i = 0; i &lt; numTerms; i++) {
<a name="line292"></a>        var hits = termHits[i];
<a name="line293"></a>        // pull off the position of the next hit of term t
<a name="line294"></a>        // (it&#39;s always the first in the array because we&#39;re shifting
<a name="line295"></a>        // hits off the front of the array as we process them)
<a name="line296"></a>        // this is the next candidate to consider for the next overall hit
<a name="line297"></a>        if (!goog.array.isEmpty(hits)) {
<a name="line298"></a>          var hitPos = hits[0];
<a name="line299"></a>
<a name="line300"></a>          // Discard any hits embedded in the previous hit.
<a name="line301"></a>          while (hitPos &gt;= 0 &amp;&amp; hitPos &lt; pos) {
<a name="line302"></a>            hits.shift();
<a name="line303"></a>            hitPos = goog.array.isEmpty(hits) ? -1 : hits[0];
<a name="line304"></a>          }
<a name="line305"></a>
<a name="line306"></a>          if (hitPos &gt;= 0 &amp;&amp; (posOfNextHit &lt; 0 || hitPos &lt; posOfNextHit)) {
<a name="line307"></a>            termIndexOfNextHit = i;
<a name="line308"></a>            posOfNextHit = hitPos;
<a name="line309"></a>          }
<a name="line310"></a>        }
<a name="line311"></a>      }
<a name="line312"></a>
<a name="line313"></a>      // Quit if there are no more hits.
<a name="line314"></a>      if (posOfNextHit &lt; 0) break;
<a name="line315"></a>
<a name="line316"></a>      // Remove the next hit from our hit list.
<a name="line317"></a>      termHits[termIndexOfNextHit].shift();
<a name="line318"></a>
<a name="line319"></a>      // Append everything from the end of the last hit up to this one.
<a name="line320"></a>      html.push(goog.string.htmlEscape(text.substr(pos, posOfNextHit - pos)));
<a name="line321"></a>
<a name="line322"></a>      // Append the annotated term.
<a name="line323"></a>      var termLen = terms[termIndexOfNextHit][0].length;
<a name="line324"></a>      var termHtml = goog.string.htmlEscape(text.substr(posOfNextHit, termLen));
<a name="line325"></a>      html.push(annotateFn(termIndexOfNextHit, termHtml));
<a name="line326"></a>
<a name="line327"></a>      pos = posOfNextHit + termLen;
<a name="line328"></a>    }
<a name="line329"></a>
<a name="line330"></a>    // Append everything after the last hit.
<a name="line331"></a>    html.push(goog.string.htmlEscape(text.substr(pos)));
<a name="line332"></a>    return html.join(&#39;&#39;);
<a name="line333"></a>  } else {
<a name="line334"></a>    return null;
<a name="line335"></a>  }
<a name="line336"></a>};
<a name="line337"></a>
<a name="line338"></a>
<a name="line339"></a>/**
<a name="line340"></a> * Converts terms to lowercase.
<a name="line341"></a> *
<a name="line342"></a> * @param {Array} terms  An array of
<a name="line343"></a> *   [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
<a name="line344"></a> * @return {!Array}  An array of
<a name="line345"></a> *   [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
<a name="line346"></a> * @private
<a name="line347"></a> */
<a name="line348"></a>goog.dom.annotate.lowercaseTerms_ = function(terms) {
<a name="line349"></a>  var lowercaseTerms = [];
<a name="line350"></a>  for (var i = 0; i &lt; terms.length; ++i) {
<a name="line351"></a>    var term = terms[i];
<a name="line352"></a>    lowercaseTerms[i] = [term[0].toLowerCase(), term[1]];
<a name="line353"></a>  }
<a name="line354"></a>  return lowercaseTerms;
<a name="line355"></a>};
</pre>


</body>
</html>
